<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/29
 * Time: 9:19
 */

namespace App\Api\V1\Controllers;

use App\Jobs\Elesticsearch;
use App\Jobs\InviteQueue;
use App\Models\HxUsers;
use App\Models\Media;
use App\Models\Usertags;
use App\Models\WechatUsers;
use App\Services\OauthService;
use App\Services\Pusher;
use App\Services\UserService;
use ClassesWithParents\D;
use Facebook\Facebook;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\Api\V1\Controllers\LoginController;
use App\Models\User;
use App\Services\Log;
use Illuminate\Support\Facades\Redis;

class OauthController extends CommonController
{

    /**
     * 1.微信对接入口
     */
    public function weixin()
    {

        if (isset($_GET["echostr"])) {
            $this->valid();
        } else {
            $this->responseMsg();
        }
    }

    /**
     * 验证微信接入
     */
    public function valid()
    {
        $oauth = config('auth.weixin');
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = $oauth['token'];//Token
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            echo $echoStr;
            exit;
        }
    }

    /**
     * 2.接入微信成功之后执行此方法
     */
    public function responseMsg()
    {
        $postStr = file_get_contents('php://input');
        if (!empty($postStr)) {
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            //消息类型分离
            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                default:
                    $result = "";
                    break;
            }
            echo $result;
        }else{
            echo "";
            exit;
        }
    }

    /**
     * @param $object
     * @return string
     * 3.获取请求事件类型
     */
    public function receiveEvent($object)
    {
        header("Content-type: text/html; charset=utf-8");
        $content = "";
        $openid   = $object->FromUserName ;  //获取用户的openid
        switch ($object->Event)
        {
            case "subscribe":
                $content  = $this->isExist($openid);
                $eventKey = $object->EventKey ;  //邀请人的标示
                $this->addUser($openid,$eventKey);
                break;
            case "unsubscribe":
                $content = "";
                break;
            case "SCAN":
                $eventKey = $object->EventKey ;  //邀请人的标示
                break;
            case "CLICK":
                if($object->EventKey) {
                    $gets = json_encode($object->EventKey);
                    $get = json_decode($gets, true);
                    $content = "APP正在内测中，即将上线，敬请期待";
                } else {
                    $content = "";
                }
                break;
            default:
                $content = "";
                break;
        }
        if(empty($content)) {
            $result = '';
        }else if(is_array($content)) {
            $result = $this->transmitNews($object, $content);
        } else {
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }


    private function isExist($openid)
    {
        if ($openid)
        {
            $user = DB::table('wechat_users')->where([['openid','=',$openid]])->value('id');
            $content = trans('notice.10216');//"亲，小爱等您好久了，马上用i微影记录您人生的点点滴滴吧！也叫上朋友跟你一起分享人生的喜悦吧！";
            /*if ($user){
                $nickname = $user->nickname;
            } else {
                $access_token = accesstoken();
                $url   = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid;
                $user  = curl_https_request($url);
                $nickname = $user['nickname'];
            }*/
            return $content;
        }
        return '感谢您关注i微影！';
    }

    //用户注册
    public  function addUser($openid,$eventKey)
    {
        /* $openid='oXS1t0dzlYAW1HDSigV1rtCw6mNY';
         $eventKey='';*/
        $openid = strval($openid);
        $access_token = accesstoken();
        $url          = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=". $openid;
        $result       = curl_https_request($url);
        $unionid = isset($result['unionid']) ? $result['unionid'] : '';
        if ($unionid) {
            $user_data = DB::table('wechat_users')->where('unionid', $unionid)->first();
        }
        if (empty($user_data)) {
            $user_data = DB::table('wechat_users')->where('openid', $openid)->first();
        }
        if(!$user_data) {
            //用户的openid不存在,则存储用户的信息
            $data['openid']        = $openid ;
            //$data['unionid']       = $result['unionid'] ?:'';  //测试公众号暂时获取不到unionid
            $data['nickname']      = $result['nickname'];
            $data['head_img']      = $result['headimgurl'];
            $data['create_time']   = time();
            $data['sex']           = $result['sex'];
            $data['language']      = $result['language'];
            $data['city']          = $result['city'];
            $data['province']      = $result['province'];
            $data['country']       = $result['country'];
            $data['unionid']       = isset($result['unionid']) ? $result['unionid'] : '';
            $data['is_subscribe']  = 1;
            //if($eventKey && gettype($eventKey)!='object'){
            $eventKey_flag = $eventKey;
            $eventKey_flag = json_encode($eventKey_flag);
            $flag = strpos($eventKey_flag,'qrscene_');
            if($flag){
                $invite = explode("_", $eventKey);
                $vid = $invite[1];  //邀请码
                $data['introducer'] = $vid;
            }
            DB::table('wechat_users')->insert($data);
        } else {
            $data = [];
            if (!$user_data->openid) {
                $data['openid'] = $openid;
            }
            if (!$user_data->unionid) {
                $data['unionid'] = $unionid;
            }
            if (!empty($data)) {
                DB::table('wechat_users')->where('id', $user_data->id)->update($data);
            }
        }
        return true;
    }

    //回复文本消息
    private function transmitText($object, $content)
    {
        $fromusername = $object->FromUserName;
        $tousername = $object->ToUserName;

        $xmlTpl = "<xml>
             <ToUserName><![CDATA[".$fromusername."]]></ToUserName>
             <FromUserName><![CDATA[".$tousername."]]></FromUserName>
             <CreateTime>".time()."</CreateTime>
             <MsgType><![CDATA[text]]></MsgType>
             <Content><![CDATA[".$content."]]></Content>
             </xml>";

        //$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $xmlTpl;
    }

    //回复图文消息
    private function transmitNews($object, $content)
    {
        if(!is_array($content))
        {
            return;
        }

        $xmlTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[news]]></MsgType>
                        <ArticleCount>1</ArticleCount>
                        <Articles>
                        <item>
                        <Title><![CDATA[%s]]></Title>
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>
                        </Articles>
                    </xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content['Title'], $content['Description'], $content['PicUrl'], $content['Url']);
        return $result;
    }

    /**
     * 微信 jssdk 算签
     */
    public function weixin_jssdk_sign(){

        $url = htmlspecialchars_decode(IT('url',true,'需传入页面URL全路径', 10217));
        $oauth = config('auth.weixin');
        $appid = $oauth['appid'];

        //缓存前缀--一定要用三个=来判断  要不然会出错
        /*if (PRODUCTION === true)$pre = 'online';
        elseif (PRODUCTION === 0)$pre = 'pre';
        else $pre = 'test';*/

        // 开始算签
        //$jsapi_ticket = S('weixin_jssdk_sign_'.$pre);
        $jsapi_ticket = cache('weixin_jssdk_sign_');
        if(empty($jsapi_ticket)){
            //$access = DL('Wechat')->get_access_token();
            $access = accesstoken();
            // 第二步根据access_token获取 ticket
            $jsapi = file_get_contents('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access.'&type=jsapi');
            $jsapi_array = json_decode($jsapi,true);
            $jsapi_ticket = $jsapi_array['ticket'];
            //S('weixin_jssdk_sign_'.$pre,$jsapi_ticket,7100);
            cache(['weixin_jssdk_sign'=>$jsapi_ticket],7190);
        }
        $noncestr = md5(rand());
        $timestamp = time();
        $js_config = array(
            'appId'	=>$appid,
            'timestamp'	=> $timestamp,
            'nonceStr'	=> $noncestr,
        );
        $sign_arr = array(
            'jsapi_ticket'	=> $jsapi_ticket,
            'noncestr'	=> $noncestr,
            'timestamp'	=> $timestamp,
            'url'		=> $url,
        );
        $signature = sha1(urldecode(http_build_query($sign_arr)));
        $js_config['signature'] = $signature;
        return json_success('ok',$js_config,10000);
    }

    public function setMenu(){

        $weixin = config('auth.weixin');
        $appid = $weixin['appid'];
        $api_url = $weixin['api_url'];  //前端地址
        //$api_url = urlencode($api_url.'api/Oauth_login_weixin');
        $url = $api_url.'api/Oauth_menu_url';
        $system = get_device_type();
        if($system == 'iPhone' || $system == 'ipad' ){
            $down_link= D('config')->where('id','=', 2)->value('download_links');
        }else{
            $down_link= D('config')->where('id','=', 1)->value('download_links');
        }

        $menu='
        {  
            "button":[  
            {  
                  "name": '.trans('notice.10218').',  
                  "sub_button":[  
                   {  
                      "type":"view",  
                      "name":'.trans('notice.10219').',  
                        "url": "http://www.i-weiying.com/#/journalism"  
                   },  
                   {  
                      "type":"view",  
                      "name":'.trans('notice.10220').',    
                      "url": "http://www.i-weiying.com/"  
                   }]  
            }, 
             {  
                  "name":'.trans('notice.10221').',    
                  "sub_button":[  
                   {  
                      "type":"view",  
                      "name":'.trans('notice.10221').',    
                      "url": "http://www.i-weiying.com/"
                   },  
                   {  
                      "type":"view",  
                      "name":'.trans('notice.10223').',    
                      "url": "http://www.i-weiying.com/#/instructions"  
                   }]  
            }, 
         {     
                "type":"view",  
                "name":'.trans('notice.10224').',      
                 "url": "http://www.i-weiying.com/#/aboutUs"  
            }]  
        } 
        ';
        //$menu = config('auth.weixin')['menu'];
        $access_token = accesstoken();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $access_token;
        $result = https_request_s($url,$menu);
        $result = json_decode($result,true);
        $result['access_token'] = $access_token;
        return json_success('ok',$result, 10000);
    }

    /**
     * @return array
     * 查看微信菜单
     */
    public function getMenu(){
        $access_token = accesstoken();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=$access_token";
        $result = https_request_s($url);
        $result = json_decode($result,true);
        $result['access_token'] = $access_token;
        return json_success('ok',$result, 10000);
    }

    public function menuUrl(){
        $auth = config('auth.weixin');
        $menu_type = IT('menu_type','index');
        $api_url = urlencode($auth['api_url'].'api/Oauth_login_weixin?menu_type='.$menu_type);
        $redirect_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$auth['appid'].'&redirect_uri='.$api_url.'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
        header("Location: $redirect_url");
        //redirect($redirect_url);
    }

    public function SharingLinks(Request $request)
    {
        $params = $request->all();
        $channel = IT('channel', 'qq'); // wx ：微信  fb:facebook

        $oath_service = new OauthService();
        switch ($channel){
            case $oath_service->oauth_type_wx:
                $redirect_url = $oath_service->create_oauth_wx_url();
                break;
            case $oath_service->oauth_type_wxm:
                $redirect_url = $oath_service->create_oauth_wx_url();
                break;
            // faceboo 中转香港域名授权
            case $oath_service->oauth_type_fb:
                $redirect_url = $oath_service->oauth_transfer_fb($params);
                break;
            case $oath_service->oauth_type_fb_hk:
                $redirect_url = $oath_service->create_oauth_fb_hk_url($params);
                break;

            // 默认跳转链接
            default:
                // 默认跳转分享首页地址
                $redirect_url = config('basic.share_url').'#/main';
                if($params['share_type'] == 'mediadetail' && isset($params['media_id']) && $params['media_id'] > 0)
                    $redirect_url = config('basic.share_url').'?id='.$params['media_id'].'&uid='.$params['uid'].'&channel='.$params['channel'].'#/index&share';
        }
        header("Location: $redirect_url");
    }

    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * 微信授权登录跳转
     */
    public function loginWeixin(){
        $web_url = config('auth.weixin')['web_url'];
        $code = IT('code');
        $uid = IT('uid', 0);
        $media_id = IT('media_id', 0);
        $share_type = IT('share_type','main');
        $channel = IT('channel','0');
        $state = IT('state', '');

        // 获取用户openid
        if(!empty($code)){
            $appid = config('auth.weixin')['appid'];
            $secret = config('auth.weixin')['appsecret'];
            $get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
            $result = curl_https_request($get_access_token_url);

            $unionid = '';
            if(isset($result['unionid']))
                $unionid = $result['unionid'];

            // 公众号静默无法获取 unionid
            if($uid > 0 && !empty($unionid))
                // 保存邀请记录
                $create_share_result = UserService::create_share_info(2, $uid, $unionid);
        }

        // 默认跳转分享首页地址
        $redirect_url = config('basic.share_url').'#/main';
        if($share_type == 'mediadetail' &&  $media_id > 0){
            $redirect_url = config('basic.share_url').'?id='.$media_id.'&uid='.$uid.'&channel='.$channel.'#/index&share';
        }
        // 跳转分享地址
        header("Location: {$redirect_url}");
    }

    public function distribute($web_url,$openid,$ticket,$menu_type, $params = []){
        if (!empty($params)) {
            $query = http_build_query($params);
        }
        switch($menu_type){
            case 'index':
                //return redirect("$web_url?openid=$openid&ticket=$ticket");
                header("Location: $web_url?openid=$openid&ticket=$ticket");
                break;
            case 'postVideo':
                //return redirect("$web_url#/postVideo?openid=$openid&ticket=$ticket");
                header("Location: $web_url#/postVideo?openid=$openid&ticket=$ticket");
                break;
            case 'about':
                header("Location: $web_url#/about?openid=$openid&ticket=$ticket");
                break;
            case 'mediaDetail':
                header("Location: $web_url?openid={$openid}&ticket={$ticket}#/videoDetails?{$query}");
                break;
            default :
                // return redirect("$web_url?openid=$openid&ticket=$ticket");
                header("Location: $web_url?openid=$openid&ticket=$ticket");
                break;
        }
    }
    //app 微信授权登陆
    public function appweixin(Request $request)
    {
        $appid = 'wx6947a0b753e61201';
        $secret = '7d49f9254ae29091704ac1f71f002538';
        //1通过code获取openID
        $code = IT('code', true, '请填写code', 10104);
        $ClientSource = IT('ClientSource',true);
        $registration_id = IT('registration_id');
        $mobile_unique_code = IT('mobile_unique_code',true,'移动设备唯一标识必填',10073);
        $Invitation_code =IT('Invitation_code');//邀请码
        $get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $result = curl_https_request($get_access_token_url);
        if (isset($result['errcode']))
            return json_error('网络繁忙',0,10103);

        $openid = $result['openid'];

        //通过openid获取UnionID
        $access_token = $result['access_token'];
        $get_unionid_token_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
        $result_unionid = curl_https_request($get_unionid_token_url);
        if (isset($result_unionid['errcode']))
            return json_error('网络繁忙',0,10103);

        // 身份标识
        $unionid = (isset($result['unionid']) && !empty($result['unionid']))
            ? $result['unionid'] : (isset($result_unionid['unionid']) && !empty($result_unionid['unionid'])  ? $result_unionid['unionid'] : '');
        if(empty(trim($unionid)) && empty(trim($openid)) )
            return json_error('登录失败',0,10083);

        // 记录微信登录表
        $wechat_users = WechatUsers::where([['unionid', '=', $unionid]])->first();
        if(empty($wechat_users))
            $wechat_users = WechatUsers::where([['app_openid', '=', $openid]])->first();
        if(empty($wechat_users)){
            $wechat_users = new WechatUsers();
            $wechat_users->nickname = isset($result_unionid['nickname']) ? $result_unionid['nickname'] : '';
            $wechat_users->head_img = isset($result_unionid['headimgurl']) ? $result_unionid['headimgurl'] : '';
            $wechat_users->sex = isset($result_unionid['sex']) ? $result_unionid['sex'] : '';
            $wechat_users->language = isset($result_unionid['language']) ? $result_unionid['language'] : '';
            $wechat_users->city = isset($result_unionid['city']) ? $result_unionid['city'] : '';
            $wechat_users->province = isset($result_unionid['province']) ? $result_unionid['province'] : '';
            $wechat_users->country = isset($result_unionid['country']) ? $result_unionid['country'] : '';
            $wechat_users->is_subscribe = 1;
            $wechat_users->create_time = time();
        }
        $wechat_users->openid = $openid;
        $wechat_users->app_openid = $openid;
        $wechat_users->unionid = $unionid;

        if(!$wechat_users->save())
            return json_error('登录失败',0,10083);

        // 用户登录
        if(!empty($unionid))
            $user_info = User::where([['unionid', '=', $unionid]])->first();
        if(!isset($user_info) || empty($user_info))
            $user_info = User::where([['app_openid', '=', $openid]])->first();
        if(!isset($user_info) || empty($user_info))
            $user_info = User::where([['openid', '=', $openid]])->first();

        $is_new = false;
        if(empty($user_info)){
            $user_info = new User();
            $user_info->name = isset($result_unionid['nickname']) ? $result_unionid['nickname'] : '';
            $user_info->avatar = isset($result_unionid['headimgurl']) ? $result_unionid['headimgurl'] : '';
            $user_info->sex = isset($result_unionid['sex']) ? $result_unionid['sex'] : '';
            $user_info->created_at = date('Y-m-d H:i:s');
            $user_info->status = 1;
            $user_info->reg_type = 1;
            $user_info->openid = $openid;
            $user_info->app_openid = $openid;
            $user_info->unionid = $unionid;
            $user_info->download_time = time();
            $is_new = true;
        }
        $user_info->updated_at = date('Y-m-d H:i:s');
        if(!$user_info->save())
            return json_error('登录失败',0,10083);

        // 创建队列
        if($is_new){
            $hx_re_user = UserService::reg_hx_user($user_info->id);
            if(!$hx_re_user)
                return json_error('登录失败',0,10083);

            if(!empty($unionid)){
                $temp_arr = [];
                // 队列
                $temp_arr['uid'] = $user_info->id;
                // 静默公众号无法获取unionid 使用md5( 昵称+头像+性别 ) 替换
                $temp_arr['operation_id'] = $unionid;
                $temp_arr['mobile_unique_code'] = $mobile_unique_code;
                $temp_arr['invitation_code'] = '';
                if(!empty($Invitation_code)){
                    $temp_arr['invitation_code'] = $Invitation_code;
                }
                dispatch((new InviteQueue(['type'=>'2', 'data'=>$temp_arr]))->onQueue('invite'));
            }

            $params = [];
            // 队列   --添加搜索索引
            $params['uid'] = $user_info->id;
            $params['name'] = isset($result_unionid['nickname']) ? $result_unionid['nickname'] : '';
            dispatch((new Elesticsearch(['type'=>'1', 'action'=>'add', 'data'=>$params]))->onQueue('eleasticsearch'));
        }

        // 校验是否需要发送下线通知
        $ticket = UserService::login_send_jpush($user_info, ['mobile_unique_code'=>$mobile_unique_code, 'registration_id'=>$registration_id, 'ClientSource'=>$ClientSource]);

        $tags = Usertags::where('uid','=',$user_info->id)->where('status','=',1)->value('tags');
        /*  if(empty($tags)){
                EE('请选则你喜欢的栏目！');
            }*/

        $data = [
            'ticket' => $ticket,
            'uid' => $user_info->id,
            'openid' => $openid,
            'tags'=> $tags
        ];
        $hx_user = HxUsers::where([['uid', '=', $user_info->id]])->first();
        $data['hx_username'] = empty($hx_user) ? '' : $hx_user->hx_username;
        $data['hx_password'] = empty($hx_user) ? '' : $hx_user->hx_password;
        return json_success('登录成功', $data, 10084);
    }

    /*
     * facebook 请求
     * */
    public function request_facebook(Request $request)
    {
        $access_token = IT('access_token');
        $fb = new Facebook([
            'app_id' => config('basic.fb_config.fb_app_id'),
            'app_secret' => config('basic.fb_config.fb_app_secret'),
            'default_graph_version' => config('basic.fb_config.fb_default_graph_version'),
        ]);

        $response = $fb->get('/me?fields=id,name,email,first_name,last_name,link,birthday,picture', $access_token);
        if(!empty($response) && trim($response->getHttpStatusCode()) == '200'){
            $response_data = $response->getDecodedBody();
            if(!isset($response_data['id']) || empty($response_data['id']))
                return json_error('登录失败', 0, 10083);
            return json_success('登录成功', $response_data, 10084);
        }
        return json_error('登录失败', [], 10083);
    }

    /*
     * facebook 登陆
     * */
    public function oauth_login_fb(Request $request)
    {
        $params = $request->all();
        $ClientSource = IT('ClientSource',true);
        $registration_id = IT('registration_id');
        $access_token = IT('access_token',true,'参数有误',10032);
        $mobile_unique_code = IT('mobile_unique_code',true,'移动设备唯一标识必填',10073);

        $url = config('basic.transfer_url').'/api/request_facebook';
        $response = curl_post($url, $params);
        $data = json_decode($response, true);

        if($data['status'] == '1' && !empty($data['data'])){
            $facebook_user_data = $data['data'];

            if(!isset($facebook_user_data['id']) || empty($facebook_user_data['id']))
                return json_error('登录失败', 0, 10083);

            $is_new = false;
            $user_info = User::where([['unionid', '=', $facebook_user_data['id']], ['reg_type', '=', '2']])->first();
            if(empty($user_info)){
                $is_new = true;
                $user_info = new User();
                $user_info->name = isset($facebook_user_data['name']) ? $facebook_user_data['name'] : '';
                $user_info->email = isset($facebook_user_data['email']) ? $facebook_user_data['email'] : '';
                $user_info->avatar = config('basic.fb_config.fb_user_url').'/'.$facebook_user_data['id'].'/picture?type=large';//(isset($facebook_user_data['picture']) && !empty($facebook_user_data['picture']['data']['url'])) ? $facebook_user_data['picture']['data']['url'] : '';
                // $user_info->sex = $fb_user_name;
                $user_info->unionid = $facebook_user_data['id'];
                $user_info->created_at = date('Y-m-d H:i:s');
                $user_info->updated_at = date('Y-m-d H:i:s');
                $user_info->reg_type = 2;
            }
            $user_info->updated_at = date('Y-m-d H:i:s');

            if($user_info->save()){
                // 创建队列
                if($is_new){
                    $hx_re_user = UserService::reg_hx_user($user_info->id);
                    if(!$hx_re_user)
                        return json_error('登录失败',0,10083);

                    $temp_arr = [];
                    // 队列
                    $temp_arr['uid'] = $user_info->id;
                    $temp_arr['operation_id'] = $facebook_user_data['id'];
                    $temp_arr['mobile_unique_code'] = $mobile_unique_code;
                    dispatch((new InviteQueue(['type'=>'2', 'data'=>$temp_arr]))->onQueue('invite'));

                    $params = [];
                    // 队列   --添加搜索索引
                    $params['uid'] = $user_info->id;
                    $params['name'] = isset($facebook_user_data['name']) ? $facebook_user_data['name'] : '';
                    dispatch((new Elesticsearch(['type'=>'1', 'action'=>'add', 'data'=>$params]))->onQueue('eleasticsearch'));
                }

                // 校验是否需要发送下线通知
                $ticket = UserService::login_send_jpush($user_info, ['mobile_unique_code'=>$mobile_unique_code, 'registration_id'=>$registration_id, 'ClientSource'=>$ClientSource]);
                $tags = Usertags::where('uid','=',$user_info->id)->where('status','=',1)->value('tags');
                /*  if(empty($tags)){
                        EE('请选则你喜欢的栏目！');
                    }*/
                $data = [
                    'ticket' => $ticket,
                    'uid' => $user_info->id,
                    'fb_uid' => $user_info->unionid,
                    'tags'=> $tags
                ];
                $hx_user = HxUsers::where([['uid', '=', $user_info->id]])->first();
                $data['hx_username'] = empty($hx_user) ? '' : $hx_user->hx_username;
                $data['hx_password'] = empty($hx_user) ? '' : $hx_user->hx_password;
                return json_success('登录成功', $data, 10084);
            }
        }
        return json_error('登录失败', [], 10083);
    }

    /*
     * facebook 授权回调
     * */
    public function oauth_fb_callback(Request $request)
    {
        $params = [];
        $redis = Redis::connection('redis_hk');
        if(!empty($params_temp = $redis->get('share_params:'.md5(get_ip())))) //取了之后删除;
            $params = json_decode($params_temp, true);

        $get_params = $request->all();
        $fb = new Facebook([
            'app_id' => config('basic.fb_config.fb_app_id'),
            'app_secret' => config('basic.fb_config.fb_app_secret'),
            'default_graph_version' => config('basic.fb_config.fb_default_graph_version'),
        ]);

        if(isset($get_params['code'])){
            $helper = $fb->getRedirectLoginHelper();
            if (isset($_GET['state']))
                $helper->getPersistentDataHandler()->set('state', $_GET['state']);

            $response = $helper->getAccessToken();
            $access_token = $response->getValue();
            $response_user = $fb->get('/me?fields=id,name,email,first_name,last_name,link,birthday,picture', $access_token);
            if(!empty($response_user) && trim($response_user->getHttpStatusCode()) == '200'){
                $response_data = $response_user->getDecodedBody();
                // 添加邀请记录
                if(isset($response_data['id']) && !empty($response_data['id']) && !empty($params) && isset($params['uid']) && !empty($params['uid']))
                    $create_share_result = curl_post(config('app.url').'/api/Oauth_invite', ['type'=>3, 'recommend_uid'=>$params['uid'], 'operation_id'=>$response_data['id']]);
            }

            // 默认跳转分享首页地址
            $redirect_url = config('basic.share_url').'#/main';
            if($params['share_type'] == 'mediadetail' && isset($params['media_id']) && $params['media_id'] > 0)
                $redirect_url = config('basic.share_url').'#/index?id='.$params['media_id'].'&share';
            // 跳转分享地址
            header("Location: {$redirect_url}");
        }
    }

    /*
     * 创建邀请记录  -facebook 请求
     * */
    public function oauth_invite(Request $request)
    {
        $type = IT('type',true,'参数有误',10032);
        $uid = IT('recommend_uid',true,'参数有误',10032);
        $operation_id = IT('operation_id',true,'参数有误',10032);
        $create_share_result = UserService::create_share_info($type, $uid, $operation_id);
        if(!$create_share_result)
            return json_error('操作失败', [], 10001);
        return json_success('操作成功', [], 10000);
    }

}




